package domain;

import GUI.DragonGUI;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import persistence.LoggerExport;
/**
 * This class is used for logging and extends the Handler class.
 * @author HTTPDragon Team
 */
class ErrorAndLogHandler extends Handler {    
  private LoggerExport export = new LoggerExport(); 

  // singleton instance
  private static ErrorAndLogHandler handler = null;
  private ErrorAndLogHandler() {
    configure();
  }
  public static synchronized ErrorAndLogHandler getInstance() {
    if (handler == null) {
      handler = new ErrorAndLogHandler();
    }
    return handler;
  }

  private void configure() {
    LogManager manager = LogManager.getLogManager();
    String className = this.getClass().getName();
    String level = manager.getProperty(className + ".level");
    String formatter = manager.getProperty(className + ".formatter");

    setLevel(level != null ? Level.parse(level) : Level.INFO);
    setFormatter(makeFormatter(formatter));
  }

  private SimpleFormatter makeFormatter(String formatterName) {
    Class c = null;
    SimpleFormatter f = new SimpleFormatter();

    try {
      c = Class.forName(formatterName);
      f = (SimpleFormatter) c.newInstance();
    } catch (Exception e) {
      f = new SimpleFormatter();
    }
    return f;
  }

    /**
     * This method styles and publishes the log messages.
     * @param record A record that should be added to the logs.
     */
  public synchronized void publish(LogRecord record) {
    String message = null;
    //check if the record is loggable
    if (!isLoggable(record)){
      return;
    }    
    message = "[" + record.getLevel() +"] " + record.getMessage();
      Date date = new Date(record.getMillis()); 
      DateFormat milisformatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); 
      String dateFormatted = milisformatter.format(date); 
      DateFormat milisformatter2 = new SimpleDateFormat("YYYY-MM"); 
      String dateFormatted2 = milisformatter2.format(date); 
      DateFormat milisformatter3 = new SimpleDateFormat("dd"); 
      String dateFormatted3 = milisformatter3.format(date); 
      
    try {
      DragonGUI.appendLog(message);
    } catch (Exception ex) {        
    }    
    
    try{    
      export.writeLine(new File("log/"+dateFormatted2),new File(dateFormatted3+"_HTTPDragon.log"), dateFormatted + " " + message);
    }catch(Exception ex){
        System.err.println(ex);    
    }

  }
  public void close() {
  }
  public void flush() {
  }
}
